import '../Scss/AnnexList.scss'

import axios from 'axios'
import dayjs from 'dayjs'
import { useState, useEffect, useRef, useCallback } from 'react'
import { Editor } from '@tinymce/tinymce-react'
import { saveAs } from 'file-saver'
import { Player, BigPlayButton } from 'video-react'
import { useEventEmitter, useBoolean, useRequest } from 'ahooks'
import { Result, Button, message, QRCode, Image, Tabs, Descriptions, Empty, Popconfirm, Table } from 'antd'

import { Http } from '../../Api'
import { API_LIST } from '../../Api/Api'
import { PrinterData, PictureStream } from '../../Configure/QRcode'
import { initPrinter } from '../../Configure/Printer'
import Loading from '../../Currency/Loading'
import { Video, DaHuaCameraPlayback } from '../../Configure/Video'
import { LiveBox } from '../../../Pages/Front/Assets/Template/HLSSource'
import { ModalBox } from '../ModalBox'
import { IndependenceUpload, FormAssembly } from '../../Form/FormAssembly'

const { GC, ttxVideoAll } = window

const fallback =
    ''

const tripartiteList = ['www.bilibili.com', 'v.qq.com']
// 附件
export const Annex = ({ data, Off }) => {
    const { url } = data
    const ImageBox = ({ url }) => <img src={url} alt={url} />
    const PdfBox = ({ url }) => <embed src={url} />
    const VideoBox = ({ url }) => (
        <Player fluid={false} width={'100%'} height={'100%'} playsInline src={url}>
            <BigPlayButton position="center" />
        </Player>
    )
    const OtherBox = () => <Result status="500" title="文件格式不支持预览" />
    const LiveVideo = ({ url }) => <LiveBox live={url} />

    const [type, setType] = useState('ImageBox')
    const AttachmentList = { ImageBox, PdfBox, VideoBox, OtherBox, LiveVideo }

    useEffect(() => {
        const regex = new RegExp(tripartiteList.join('|'), 'i')
        if (!url) setType('OtherBox')
        var suffix = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
        if (regex.test(url)) {
            Off && Off()
            window.open(url)
        } else if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif') setType('ImageBox')
        else if (suffix === 'pdf') setType('PdfBox')
        else if (suffix === 'mp4') setType('VideoBox')
        else if (suffix === 'm3u8') setType('LiveVideo')
        else setType('OtherBox')
    }, [Off, url])

    return (
        <div className="Enclosure">
            {(() => {
                const Template = AttachmentList[type]
                return <Template url={url} />
            })()}
        </div>
    )
}

export const AnnexMore = ({ data }) => {
    const { list } = data.data
    const [OptionsCall, setOptionsCall] = useState()
    return (
        <div className="AnnexMore">
            {list.map(({ uuid, tableName, fileUrl }) => (
                <div
                    key={uuid}
                    onClick={() => {
                        setOptionsCall({ type: 'Annex', data: { url: fileUrl, title: tableName, width: '90vw' } })
                    }}
                >
                    {tableName}
                </div>
            ))}
            <ModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

// 打印试验二维码
export const PrintQRcode = ({ data }) => {
    const [PrintState, { setTrue: PrintTrue, setFalse: PrintFalse }] = useBoolean(false)
    const { data: record, url } = data
    const UrlEvent = useEventEmitter()
    const [Url, setUrl] = useState()
    useEffect(
        () => setUrl(PictureStream(API_LIST()['getLabSampleQRImage'], `SampleItemUuid=${record.uuid}`, UrlEvent)),
        [record, UrlEvent],
    )
    UrlEvent.useSubscription(val => setUrl(val))
    const MarkEvent = useEventEmitter()
    MarkEvent.useSubscription(() => PrintFalse())
    return (
        <div className="codeBox">
            <img src={Url} alt="" />
            <div>
                <Button type="primary" size="large" onClick={() => saveAs(Url, '二维码.png')}>
                    下载二维码
                </Button>
                {url && (
                    <Button
                        type="primary"
                        size="large"
                        onClick={() => {
                            PrintTrue()
                            const [type, size, content, printDensity, printLabelType, printMode, count] =
                                PrinterData(Url)[url]
                            initPrinter(type, size, content, printDensity, printLabelType, printMode, count, MarkEvent)
                        }}
                    >
                        打印二维码
                    </Button>
                )}
            </div>
            {PrintState && (
                <div className="MarkBox">
                    <Loading
                        text="打印中..."
                        color={{ background: 'radial-gradient(rgba(0,0,0,0.7), rgba(255,255,255,1))' }}
                    />
                </div>
            )}
        </div>
    )
}

// 下载普通二维码
export const OrdinaryQRCode = ({ data }) => {
    const downloadQRCode = () => {
        const canvas = document.getElementById('myQRcode')?.querySelector('canvas')
        if (canvas) {
            const url = canvas.toDataURL()
            const a = document.createElement('a')
            a.download = 'QRCode.png'
            a.href = url
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        }
    }
    return (
        <div className="OrdinaryQRCode" id="myQRcode">
            <QRCode style={{ marginBottom: 16 }} size={552} iconSize={100} errorLevel="H" value={data.data.url} />
            <Button type="primary" onClick={downloadQRCode}>
                下载二维码
            </Button>
        </div>
    )
}

export const UrlQRCode = ({ data }) => {
    const { qrCodeImage, tableName } = data.data.record
    const Submit = () => {
        fetch(qrCodeImage)
            .then(response => response.blob())
            .then(blob => saveAs(blob, tableName + '.jpg'))
    }
    return (
        <div className="UrlQRCode">
            <img src={qrCodeImage} alt="" />
            <div className="Submit" onClick={Submit}>
                <Button type="primary">下载二维码</Button>
            </div>
        </div>
    )
}

// 打开excel
export const OpenExcel = ({ data }) => {
    const [messageApi, contextHolder] = message.useMessage()
    const [loading, setLoading] = useState(false)
    const [ExcelName, setExcelName] = useState([])
    const [spread, setSpread] = useState()
    const [SaveStatus, setSaveStatus] = useState(false)
    const [SubmitUrl, setSubmitUrl] = useState()
    const [params, setParams] = useState()
    const ExcelBox = useRef()
    const saveExcel = () => {
        const excelIo = new GC.Spread.Excel.IO()
        excelIo.save(spread.toJSON(), e => saveAs(e, ExcelName))
    }
    const submitExcel = () => {
        setLoading(true)
        const { pos } = data.data
        const excelIo = new GC.Spread.Excel.IO()
        excelIo.save(spread.toJSON(), e => {
            const forms = new FormData()
            const { type } = e
            const file = new File([e], ExcelName, { type })
            forms.append('File', file)
            forms.append('FileType', 3)
            const urlSearchParams = new URLSearchParams(params)
            const url = `${API_LIST()[pos || 'posSampleItemUploadTestDataEXCEL']}?` + urlSearchParams.toString()
            axios.post(url, forms).then(() => messageApi.success('文件上传成功'))
            setLoading(false)
        })
    }

    useEffect(() => {
        const { url, save, submit, pos, ...params } = data.data
        const spread = new GC.Spread.Sheets.Workbook(ExcelBox.current, { sheetCount: 1 })
        setSaveStatus(save)
        setSubmitUrl(submit)
        setSpread(spread)
        setParams(params)

        axios.get(API_LIST()[url], { params, responseType: 'blob' }).then(({ data, headers }) => {
            let textName = ''
            const nameArr = headers['content-disposition'].split(';')
            nameArr.forEach(item => {
                if (item.indexOf("filename*=UTF-8''") !== -1) textName = decodeURI(item.split("filename*=UTF-8''")[1])
            })
            setExcelName(textName)
            const excelIo = new GC.Spread.Excel.IO()
            excelIo.open(data, workbookObj => spread.fromJSON(workbookObj))
        })
    }, [data])
    return (
        <div className="OpenExcel">
            {contextHolder}
            <div className="Excel" ref={ExcelBox} />
            <div className="options">
                {SaveStatus && <Button onClick={saveExcel}>下载Excel</Button>}
                {SubmitUrl && (
                    <Button loading={loading} type="primary" onClick={submitExcel}>
                        保存信息
                    </Button>
                )}
            </div>
        </div>
    )
}

// 监控画面
export const MonitorVideo = ({ data }) => {
    const { runAsync } = useRequest(Http, { manual: true })
    const [VideoList, setVideoList] = useState([])
    useEffect(() => {
        const { url, ...props } = data.data
        runAsync({ url, data: props }).then(res => setVideoList(res.list))
    }, [data, runAsync])

    return (
        <div className="MonitorVideo">
            {VideoList.length !== 0 ? (
                <div className="SeeLabVideoModalScroll" style={{ width: VideoList?.length * 816 }}>
                    {VideoList.map((item, index) => (
                        <div key={index}>
                            {(() => {
                                const { cameraFactory, startTime, endTime } = item
                                if (cameraFactory === 1) {
                                    const begin = dayjs(startTime).format('YYYYMMDDHHmmss')
                                    const end = dayjs(endTime).format('YYYYMMDDHHmmss')
                                    return (
                                        <Video
                                            data={item}
                                            date={new Date().getTime()}
                                            playback={`&begin=${begin}&end=${end}`}
                                        />
                                    )
                                } else {
                                    return <DaHuaCameraPlayback data={item} />
                                }
                            })()}
                        </div>
                    ))}
                </div>
            ) : (
                <Result status="500" title="暂无监控数据" />
            )}
        </div>
    )
}

// 富文本编辑器
export const RichTextEditor = ({ data }) => {
    const [messageApi, contextHolder] = message.useMessage()
    const { record } = data.data
    const { uuid } = record
    const editorRef = useRef(null)
    const { runAsync: getData } = useRequest(Http, { manual: true })
    const { runAsync: putInfoManage } = useRequest(Http, { manual: true })
    const [loading, { setTrue, setFalse }] = useBoolean(false)

    const [initialValue, setInitialValue] = useState()

    useEffect(() => {
        getData({ url: 'getInfoManageGetOneInfoManage', data: { uuid } }).then(res => {
            const [{ infoContent }] = res
            setInitialValue(infoContent || '<p>请在这里输入文章内容.</p>')
        })
    }, [uuid, getData])

    const submit = () => {
        setTrue()
        const data = {
            ...record,
            infoContent: editorRef.current.getContent(),
        }
        putInfoManage({ url: 'putInfoManage', data, path: [uuid] }).then(res => {
            messageApi.success('内容保存成功过')
            setFalse()
        })
    }

    return (
        <div className="RichTextEditor">
            {contextHolder}
            <Editor
                apiKey="5b9brap9x1rvhy1ixyk6bzvxi3ensl97vz0q3g5pg3y88xfo"
                onInit={(_, editor) => (editorRef.current = editor)}
                initialValue={initialValue}
                init={{
                    language: 'zh_CN',
                    menubar: true,
                    branding: false,
                    automatic_uploads: true,
                }}
            />
            <Button type="primary" loading={loading} onClick={submit}>
                保存内容
            </Button>
        </div>
    )
}

// 中路的视频对讲
export const ZLVideoModal = ({ data, Off }) => {
    useEffect(() => {
        const initFlash = () => {
            const { swfobject } = window
            const { record, jsession } = data.data
            const { deviceSerial } = record
            if (
                typeof swfobject == 'undefined' ||
                swfobject.getObjectById('cmsv6flash') == null ||
                typeof swfobject.getObjectById('cmsv6flash').setWindowNum == 'undefined'
            )
                setTimeout(initFlash, 50)
            else {
                swfobject.getObjectById('cmsv6flash').setLanguage('cn.xml')
                swfobject.getObjectById('cmsv6flash').setWindowNum(40)
                swfobject.getObjectById('cmsv6flash').setWindowNum(1)
                swfobject.getObjectById('cmsv6flash').setServerInfo('cmsv.e-jt.cn', '6605')
                //停止播放视频
                swfobject.getObjectById('cmsv6flash').stopVideo(0)
                swfobject.getObjectById('cmsv6flash').setVideoInfo(0, 'vehicle1-CH1')
                swfobject.getObjectById('cmsv6flash').startVideo(0, jsession, deviceSerial, 0, 1, true)
                // swfobject.getObjectById('cmsv6flash').startListen(jsession, deviceSerial, 0, 'cmsv.e-jt.cn', '6605')
            }
        }
        var params = { lang: 'zh-cn' }
        ttxVideoAll.init('cmsv6flash', 952, 600, params, 'auto')
        initFlash()
    }, [data])

    const close = () => {
        const closeFunc = () => {
            const { swfobject } = window
            if (
                typeof swfobject == 'undefined' ||
                swfobject.getObjectById('cmsv6flash') == null ||
                typeof swfobject.getObjectById('cmsv6flash').setWindowNum == 'undefined'
            ) {
                setTimeout(closeFunc, 50)
            } else {
                swfobject.getObjectById('cmsv6flash').stopTalkback()
                swfobject.getObjectById('cmsv6flash').stopVideo(0)
                Off()
            }
        }
        closeFunc()
    }

    return (
        <div className="ZLVideoModal">
            <div id="cmsv6flash" />
            <div className="Button">
                <Button type="primary" onClick={close}>
                    停止对讲
                </Button>
            </div>
        </div>
    )
}

export const MonitoringModal = ({ data }) => {
    const { data: camera } = data
    return (
        <div className="MonitoringModal">
            <Video data={camera} />
        </div>
    )
}

const FileManagementType = {
    // 人员配置信息
    person: {
        API: {
            getUrl: 'getPersonAttachmentTypedAttachments',
            posUrl: 'posPersonAttachmentBatch',
            delUrl: 'delPersonAttachment',
        },

        ADDUrl: { url: 'getSecurityActivityPersonSecurityActivityList', path: 'uuid' },
        posPrame: { uuid: 'personUuid', attuuid: 'attachmentUuid', type: 'personAttachmentType' },
        infoItems: record => [
            { key: '1', label: '人员姓名', children: record.tableName },
            { key: '2', label: '人员类别', children: record.personTypeName },
            { key: '3', label: '组织机构', children: record.organizationName },

            { key: '4', label: '身份证', children: record.idCard },
            { key: '5', label: '手机号码', children: record.mobile },
            { key: '6', label: '年龄', children: record.age },
        ],
        DataMapping: {
            A01: '1',
            A02: '2',
            A03: '3',
            A04: '4',
            A05: '5',
            C01: '6',
            C02: '7',
            C03: '8',
            C04: '9',
            C05: '10',
            C06: '11',
            D01: '12',
            D03: '13',
        },
        ADDMapping: {
            B01: 'securityActivityList',
            B02: '1',
            B03: '2',
            B04: '3',
            D02: 'attendance',
            D04: 'wage',
        },
        DeleteMapping: ['A01', 'A02', 'A03', 'A04', 'A05', 'C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'D01', 'D03'],
        ApiList: {
            A01: { pos: '1', type: '1', valueFile: [1, 2, 3, 4, 5] },
            A02: { pos: '2', type: '2', valueFile: [1, 2, 3, 4, 5] },
            A03: { pos: '3', type: '3', valueFile: [1, 2, 3, 4, 5] },
            A04: { pos: '4', type: '4', valueFile: [1, 2, 3, 4, 5] },
            A05: { pos: '5', type: '5', valueFile: [1, 2, 3, 4, 5] },
            C01: { pos: '6', type: '6', valueFile: [1, 2, 3, 4, 5] },
            C02: { pos: '7', type: '7', valueFile: [1, 2, 3, 4, 5] },
            C03: { pos: '8', type: '8', valueFile: [1, 2, 3, 4, 5] },
            C04: { pos: '9', type: '9', valueFile: [1, 2, 3, 4, 5] },
            C05: { pos: '10', type: '10', valueFile: [1, 2, 3, 4, 5] },
            C06: { pos: '11', type: '11', valueFile: [1, 2, 3, 4, 5] },
            D01: { pos: '12', type: '12', valueFile: [1, 2, 3, 4, 5] },
            D03: { pos: '13', type: '13', valueFile: [1, 2, 3, 4, 5] },
        },
        items: [
            { key: 'A00', label: '人员相关信息' },
            { key: 'B00', label: '教育培训' },
            { key: 'C00', label: '告知、承诺、合同、协议等' },
            { key: 'D00', label: '考勤、工资等' },
        ],
        TabsOptions: {
            A00: [
                { key: 'A01', label: '身份证' },
                { key: 'A02', label: '体检表' },
                { key: 'A03', label: '用工协议' },
                { key: 'A04', label: '其他证件' },
                { key: 'A05', label: '进退场确认书' },
            ],
            B00: [
                { key: 'B01', label: '参加培训台账' },
                { key: 'B02', label: '培训考试试卷' },
                { key: 'B03', label: '培训评估表' },
                { key: 'B04', label: '安全技术交底' },
            ],
            C00: [
                { key: 'C01', label: '岗位风险告知' },
                { key: 'C02', label: '职业健康告知' },
                { key: 'C03', label: '个人安全承诺' },
                { key: 'C04', label: '个人安全协议' },
                { key: 'C05', label: '安全责任书' },
                { key: 'C06', label: '消防责任书' },
            ],
            D00: [
                { key: 'D01', label: '技术交底台账' },
                { key: 'D02', label: '考勤表' },
                { key: 'D03', label: '请假申请' },
                { key: 'D04', label: '工资确认表' },
            ],
        },
        AddTemplate: { B01: 'Table', D02: 'Table', D04: 'Table' },
        columnsList: {
            B01: [
                { title: '组织机构', dataIndex: 'organizationName' },
                { title: '主题', dataIndex: 'tableName' },
                { title: '活动时长', dataIndex: 'interval' },
                { title: '开始时间', dataIndex: 'startTime' },
                { title: '结束时间', dataIndex: 'endTime' },
            ],
            D02: [
                { dataIndex: 'organizationName', title: '组织机构' },
                { dataIndex: 'attendanceTime', title: '考勤日期' },
            ],
            D04: [
                { dataIndex: 'organizationName', title: '组织机构', width: 200 },
                { dataIndex: 'laborCompany', title: '劳务公司', width: 200 },
                { dataIndex: 'personName', title: '姓名', width: 200 },
                { dataIndex: 'idCard', title: '身份证号', width: 200 },
                { dataIndex: 'creditCardNum', title: '银行卡号', width: 200 },
                { dataIndex: 'bankName', title: '开户委', width: 200 },
                { dataIndex: 'personTypeName', title: '岗位', width: 200 },
                { dataIndex: 'dailyWage', title: '日工资', width: 200 },
                { dataIndex: 'attendanceDayCount', title: '出勤工日', width: 200 },
                { dataIndex: 'wage', title: '实发工资', width: 200 },
                { dataIndex: 'beginTime', title: '开始日期', width: 200 },
                { dataIndex: 'endTime', title: '结束日期', width: 200 },
            ],
        },
    },
    // 机械配置信息
    machine: {
        API: {
            getUrl: 'getMachineAttachmentTypedAttachments',
            posUrl: 'posMachineAttachmentBatch',
            delUrl: 'delMachineAttachment',
        },
        ADDUrl: { url: 'getPersonAttachmentTypedAttachmentsByIdCard', path: 'driverIdentityCard' },

        posPrame: { uuid: 'machineUuid', attuuid: 'attachmentUuid', type: 'machineAttachmentType' },
        infoItems: record => [
            { key: '1', label: '机械名称', children: record.tableName },
            { key: '2', label: '进厂编号', children: record.code },
            { key: '3', label: '机械类别', children: record.machineTypeName },
            { key: '15', label: '车牌号', children: record.carNumber },
            { key: '5', label: '车主姓名', children: record.ownerName },
            { key: '6', label: '车主电话', children: record.ownerMobile },
            { key: '7', label: '司机姓名', children: record.driverName },
            { key: '8', label: '司机身份证', children: record.driverIdentityCard },
            { key: '9', label: '司机电话', children: record.driverMobile },
            { key: '4', label: '生产日期', children: record.manufactureDate },
            { key: '10', label: '进场时间', children: record.entryTime },
            { key: '11', label: '退场时间', children: record.leaveTime },
            { key: '12', label: '使用年限', children: record.durableYears },
            { key: '13', label: 'Gps设备序列号', children: record.gpsDeviceSerial },
            { key: '14', label: '摄像头名称', children: record.cameraName },
            { key: '16', label: '卡号', children: record.cardNumber },
        ],
        DataMapping: {
            A01: '1',
            A02: '2',
            A03: '3',
            A04: '4',
            A05: '5',
            A06: '6',
        },
        ADDMapping: {
            B01: '1',
            B02: '2',
            B03: '3',
            B04: '4',
            B05: '5',
        },
        DeleteMapping: ['A01', 'A02', 'A03', 'A04', 'A05', 'A06'],
        ApiList: {
            A01: { pos: '1', type: '1', valueFile: [1, 2, 3, 4, 5] },
            A02: { pos: '2', type: '2', valueFile: [1, 2, 3, 4, 5] },
            A03: { pos: '3', type: '3', valueFile: [1, 2, 3, 4, 5] },
            A04: { pos: '4', type: '4', valueFile: [1, 2, 3, 4, 5] },
            A05: { pos: '5', type: '5', valueFile: [1, 2, 3, 4, 5] },
            A06: { pos: '6', type: '6', valueFile: [1, 2, 3, 4, 5] },
        },
        items: [
            { key: 'A00', label: '机械信息' },
            { key: 'B00', label: '人员信息' },
        ],
        TabsOptions: {
            A00: [
                { key: 'A01', label: '机械照片' },
                { key: 'A02', label: '进出场记录表' },
                { key: 'A03', label: '验收记录表' },
                { key: 'A04', label: '维修记录表' },
                { key: 'A05', label: '保养记录表' },
                { key: 'A06', label: '档案记录表' },
            ],
            B00: [
                { key: 'B01', label: '身份证' },
                { key: 'B02', label: '体检表' },
                { key: 'B03', label: '用工协议' },
                { key: 'B04', label: '其他证件' },
                { key: 'B05', label: '进退场确认书' },
            ],
        },
        AddTemplate: {},
    },
}

// 人员档案 && 机械档案
export const FileManagement = ({ data }) => {
    const { record, classification, options } = data.data
    const { uuid, fileUrl } = record

    const {
        API,
        ADDUrl,
        posPrame,
        items,
        infoItems,
        DataMapping,
        ADDMapping,
        DeleteMapping,
        ApiList,
        TabsOptions,
        AddTemplate,
        columnsList,
    } = FileManagementType[classification]
    const { getUrl, posUrl, delUrl } = API

    const [TabsActive, setTabsActive] = useState('A00')
    const [LeftTabsActive, setLeftTabsActive] = useState('A01')

    const [Data, setData] = useState({})
    const [AddData, setAddData] = useState({})

    const { runAsync: getData } = useRequest(Http, { manual: true, onSuccess: res => setData(res) })
    const { runAsync: addData } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setAddData(res)
        },
    })
    const { runAsync: posData } = useRequest(Http, { manual: true })
    const { runAsync: delData } = useRequest(Http, { manual: true })

    const GetData = useCallback(() => {
        getData({ url: getUrl, path: [uuid] })
        if (ADDUrl) addData({ url: ADDUrl.url, data: {}, path: [record[ADDUrl.path]] })
    }, [getData, getUrl, uuid, ADDUrl, addData, record])

    const UploadEvent = useEventEmitter()
    UploadEvent.useSubscription(val => {
        const { type, uuidList } = val
        if (uuidList.length !== 0) {
            const data = uuidList.map(itme => ({
                [posPrame.uuid]: uuid,
                [posPrame.attuuid]: itme,
                [posPrame.type]: type,
            }))
            posData({ url: posUrl, data }).then(GetData)
        }
    })

    // 左侧通用Tabs
    const LeftTabs = ({ items }) => (
        <Tabs tabPosition="left" activeKey={LeftTabsActive} items={items} onChange={e => setLeftTabsActive(e)} />
    )

    const TabsTemplate = ({ items }) => {
        const [OptionsCall, setOptionsCall] = useState()
        const onOpen = e => {
            const { originalName, fileUrl } = e
            setOptionsCall({ type: 'Annex', data: { url: fileUrl, title: originalName, width: '90vw' } })
        }
        const onDelete = e => {
            delData({ url: delUrl, path: [e] }).then(() => GetData())
        }
        return (
            <>
                <LeftTabs items={items} />
                <div className="rightList">
                    {ApiList[LeftTabsActive]?.pos && !options && (
                        <IndependenceUpload
                            type={ApiList[LeftTabsActive].type}
                            valueFile={ApiList[LeftTabsActive].valueFile}
                            UploadEvent={UploadEvent}
                        />
                    )}
                    <div className="AnnexTemplate">
                        {(() => {
                            const DataOne = Data[DataMapping[LeftTabsActive]]
                            const DataTwo = AddData[ADDMapping[LeftTabsActive]]
                            const Template = ({ data }) => {
                                switch (AddTemplate[LeftTabsActive]) {
                                    case 'Table':
                                        if (data)
                                            return (
                                                <Table
                                                    columns={columnsList[LeftTabsActive]}
                                                    dataSource={data}
                                                    rowKey="uuid"
                                                    scroll={{ x: 500, y: 400 }}
                                                />
                                            )
                                        else return <Empty />
                                    default:
                                        return (
                                            <>
                                                {data.map(({ uuid, attachment }) => (
                                                    <div key={uuid} className="AnnexList">
                                                        <div onClick={() => onOpen(attachment)}>
                                                            {attachment.originalName}
                                                        </div>
                                                        {DeleteMapping.includes(LeftTabsActive) && !options && (
                                                            <Popconfirm
                                                                title="是否确认删除附件"
                                                                onConfirm={() => onDelete(uuid)}
                                                                okText="删除"
                                                                cancelText="取消"
                                                            >
                                                                <Button type="link" danger>
                                                                    删除
                                                                </Button>
                                                            </Popconfirm>
                                                        )}
                                                    </div>
                                                ))}
                                            </>
                                        )
                                }
                            }
                            return DataOne || DataTwo ? <Template data={DataOne || DataTwo} /> : <Empty />
                        })()}
                        <ModalBox OptionsCall={OptionsCall} />
                    </div>
                </div>
            </>
        )
    }

    const onTabsChange = e => {
        setTabsActive(e)
        setLeftTabsActive(e[0] + '01')
    }

    useEffect(() => {
        GetData()
    }, [GetData])

    return (
        <div className="PersonFiles">
            <div className="base">
                {classification === 'person' && <Image width={200} height={200} src={fileUrl} fallback={fallback} />}
                <div className="info">
                    <Descriptions layout="vertical" items={infoItems(record)} />
                </div>
            </div>
            <div className="list">
                <Tabs activeKey={TabsActive} items={items} onChange={onTabsChange} />
                <div className="details">
                    <TabsTemplate items={TabsOptions[TabsActive]} />
                </div>
            </div>
        </div>
    )
}

export const SciencesDetails = ({ data }) => {
    const { uuid, tableName, organizationName, dictionaryName } = data.data.record

    const AnnexCon = {
        added: 'posScienceAttachments',
        initialValues: { scienceUuid: uuid },
        columns: [
            {
                title: 'scienceUuid',
                dataIndex: 'scienceUuid',
                valueType: 'hidden',
                hideInTable: true,
            },
            {
                dataIndex: 'attachmentUuid',
                title: '文件附件',
                valueType: 'upload',
                valueFile: [1, 2, 3, 4],
                fileUrl: 'fileUrl',
                rules: true,
                hideInTable: true,
            },
            {
                dataIndex: 'fileUrl',
                title: '文件附件',
                valueType: 'hidden',
                hideInSearch: true,
                hideInTable: true,
                hideInAdded: true,
                hideInModify: true,
                width: 400,
            },
        ],
    }
    const FlowCon = {
        added: 'posScienceDetails',
        initialValues: { scienceUuid: uuid },
        columns: [
            {
                title: '组织机构',
                dataIndex: 'scienceUuid',
                valueType: 'hidden',
                render: () => <div>{organizationName}</div>,
            },
            {
                title: '名称',
                dataIndex: 'tableName',
                valueType: 'input',
            },
            {
                title: '排序',
                dataIndex: 'sortId',
                valueType: 'inputNumber',
            },
            {
                title: '计划日期',
                dataIndex: 'planTime',
                valueType: 'Date',
            },
            {
                title: '完成日期',
                dataIndex: 'finishTime',
                valueType: 'Date',
            },
            {
                title: '操作',
                valueType: 'systemOperation',
                fixed: 'right',
                hideInSearch: true,
                hideInAdded: true,
                hideInModify: true,
                render: ({ uuid }) => {
                    return [
                        <Popconfirm
                            title="删除流程"
                            description="是否删除该流程?"
                            onConfirm={() => onDeleteFlow(uuid)}
                            okText="删除"
                            cancelText="取消"
                        >
                            <Button danger type="link">
                                删除
                            </Button>
                        </Popconfirm>,
                    ]
                },
            },
        ],
    }

    const [Annex, setAnnex] = useState([])
    const [Flow, setFlow] = useState([])

    const [OptionsCall, setOptionsCall] = useState()
    const [configure, setConfigure] = useState()

    const { runAsync: getAnnex } = useRequest(Http, {
        manual: true,
        onSuccess: res => setAnnex(res.list),
    })

    const { runAsync: getFlow } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            console.log('流程', res)
            setFlow(res.list)
        },
    })

    const { runAsync: DelAnnex } = useRequest(Http, {
        manual: true,
        onSuccess: res => getAnnex({ url: 'getScienceAttachments', data: { scienceUuid: uuid } }),
    })

    const { runAsync: DelFlow } = useRequest(Http, {
        manual: true,
        onSuccess: res => getFlow({ url: 'getScienceDetails', data: { scienceUuid: uuid } }),
    })

    useEffect(() => {
        getAnnex({ url: 'getScienceAttachments', data: { scienceUuid: uuid } })
        getFlow({ url: 'getScienceDetails', data: { scienceUuid: uuid } })
    }, [getAnnex, getFlow, uuid])

    const items = [
        { key: 1, label: '组织机构', children: organizationName },
        { key: 2, label: '名称', children: tableName },
        { key: 3, label: '类别', children: dictionaryName },
    ]

    const AddAnnex = () => {
        setConfigure(AnnexCon)
        setOptionsCall({ type: 'Add', data: { title: '添加附件' } })
    }
    const AddFlow = () => {
        setConfigure(FlowCon)
        setOptionsCall({ type: 'Add', data: { title: '添加附件' } })
    }

    const reloadEvent = useEventEmitter()
    reloadEvent.useSubscription(val => {
        getAnnex({ url: 'getScienceAttachments', data: { scienceUuid: uuid } })
        getFlow({ url: 'getScienceDetails', data: { scienceUuid: uuid } })
    })

    const onOpenAnnex = url => {
        setOptionsCall({ type: 'Annex', data: { title: '查看附件', url } })
    }

    const onDeleteAnnex = uuid => {
        DelAnnex({ url: 'delScienceAttachments', path: [uuid] })
    }

    const onDeleteFlow = uuid => {
        DelFlow({ url: 'delScienceDetails', path: [uuid] })
    }

    return (
        <div className="SciencesDetails">
            <Descriptions items={items} />
            <div className="Details">
                <div className="Annex">
                    <div className="Title">
                        <div>附件详情</div>
                        <Button type="primary" onClick={AddAnnex}>
                            添加
                        </Button>
                    </div>
                    <div className="Item">
                        {Annex.map(({ uuid, fileUrl, originalName }) => (
                            <div className="Annexitem" key={uuid}>
                                <div onClick={() => onOpenAnnex(fileUrl)}>{originalName}</div>
                                <Popconfirm
                                    title="附件删除"
                                    description="是否删除该附件?"
                                    onConfirm={() => onDeleteAnnex(uuid)}
                                    okText="删除"
                                    cancelText="取消"
                                >
                                    <Button danger type="link">
                                        删除
                                    </Button>
                                </Popconfirm>
                            </div>
                        ))}
                    </div>
                </div>
                <div className="Flow ">
                    <div className="Title">
                        <div>流程详情</div>
                        <Button type="primary" onClick={AddFlow}>
                            添加
                        </Button>
                    </div>
                    <div className="Item">
                        <Table columns={FlowCon.columns} dataSource={Flow} rowKey="uuid" scroll={{ y: 400 }} />
                    </div>
                </div>
            </div>
            <ModalBox OptionsCall={OptionsCall} configure={configure} reloadEvent={reloadEvent} />
        </div>
    )
}
